package com.leetcode.leetcode1;

import java.util.*;

/**
 * @program: 三数之和
 * @author: luhd
 * @create: 2021-08-26
 */
public class Practice15 {
    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        //int[] nums1 = {-4,-1,-1,0,1,2};
        List<List<Integer>> lists = threeSum(nums);
        System.out.println(lists);
    }
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        int len = nums.length;
        if(nums==null || len<3) return lists;
        // 首先对数组进行排序
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if(nums[i]>0) break;
            if(i>0 && nums[i]==nums[i-1]) continue;
            // 设立两个指针，其中一个以i为基准（L = i+1）
            int L = i+1;
            int R = len-1;
            while(L<R){
                int sum = nums[i]+nums[L]+nums[R];
                if(sum ==0){
                    lists.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while(L<R && nums[L]==nums[L+1]) L++;
                    while (L < R && nums[R] == nums[R-1]) R--;
                    L++;
                    R--;
                }
                else if(sum<0) L++;
                else if(sum>0) R--;
            }
        }
        return lists;
    }
}
